std::scoped_lock
basically provides the same feature as std::lock_guard
, but is more generic: It can lock several mutexes
at the same time, with a deadlock prevention mechanism (see S5524). The equivalent code to perform simultaneous locking with
std::lock_guard
is significantly more complex. Therefore, it is simpler to use std::scoped_lock
all the time, even when
locking only one mutex (there will be no performance impact).
Noncompliant code example
void f1(std::mutex &m1) {
std::lock_guard lock{m1}; // Noncompliant
// Do some work
}
void f2(std::mutex &m1, std::mutex &m2)
std::lock(m1, m2);
std::lock_guard<std::mutex> lock1{m1, std::adopt_lock}; // Noncompliant
std::lock_guard<std::mutex> lock2{m2, std::adopt_lock}; // Noncompliant
// Do some work
}
Compliant solution
void f1(std::mutex &m1) {
std::scoped_lock lock{m1}; // Compliant
// Do some work
}
void f2(std::mutex &m1, std::mutex &m2)
std::scoped_lock lock{m1, m2}; // Compliant, and more simple
// Do some work
}